package reese.think_in_java.java_21_thread;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * ***********************************************************
 *
 * @类名 : reese.think_in_java.java_21_thread.类名
 * @DESCRIPTION : 这家伙太懒啥都没写
 * @AUTHOR :  一个风情万种的男子
 * @DATE : 2016/6/2
 * ***********************************************************
 */

//Synchronize the entire method
class ExplicitPairManager1 extends PairManager {

    private Lock lock = new ReentrantLock();


    @Override
    public synchronized void increment() {
        lock.lock();
        try {
            p.incrementX();
            p.incrementY();
            store(getPair());
        } finally {
            lock.unlock();
        }
    }
}

// use a critical section
class ExplicitPairManager2 extends PairManager {
    private Lock lock = new ReentrantLock();

    @Override
    public void increment() {
        Pair temp;
        lock.lock();
        try {
            p.incrementX();
            p.incrementY();
            temp = getPair();
        }finally {
            lock.unlock();
        }
        store(temp);

    }
}

public class ExplicitCriticalSection {
    public static void main(String[] args) {
        PairManager
                pairManager1 = new ExplicitPairManager1(),
                pairManager2 = new ExplicitPairManager2();
        CriticalSection.testApproaches(pairManager1,pairManager2);

    }
}
